package com.bing.habit.service.impl;

import com.bing.habit.model.constant.CachePrefix;
import com.bing.habit.service.ClockInLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author: xujiabing
 * @date: 2024-10-01 19:36
 * @description springboot框架定时任务
 */
@Service
@Slf4j
public class ScheduledTask {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private ClockInLogService clockInLogService;

    /**
     * @description: 定时删除习惯打卡日志图片-早上6点开始执行
     * @author: xujiabing
     * @date: 2024-10-01 19:38
     * @param:
     * @return: void
     */
    @Scheduled(cron = "0 0 6 * * ?") //每天早上6点执行
    //@Scheduled(fixedRate = 10000) // 每10秒执行一次
    //@Scheduled(cron = "0 0 15 * * ?") //每天15点执行
    public void scheduledDelImgs() {
        log.info("定时任务开始执行,开始删除图片");
        //匹配key
        String pattern = CachePrefix.HABIT_KEY.getPrefix() + "*";
        Set<String> keys = redisTemplate.keys(pattern);
        //不存在删除的图片url
        if (keys.size() == 0) {
            log.info("定时任务执行结束,没有要删除的习惯图片");
            return;
        }
        for (String key : keys) {
            List<String> list = (ArrayList) redisTemplate.opsForValue().get(key);
            for (String url : list) {
                log.info("执行删除图片 = " + url);
                clockInLogService.delUploadFile(url);
            }
            //删除一个习惯url list后，从redis中删除
            redisTemplate.delete(key);
        }
    }
}
